(function(){
  jsonFlickrApi = function(results){
     //flickr_webapp.splash(results.photos.photo[0]);
     flickr_webapp.splash(results);
  }
  flickr_webapp = function(){
    var _w,_d,_h,_s,_g,_s,_imgs,_focus; //function scoped vars
    var _BUFFER = 60; //number if images to cache
    var _PER_PAGE = 15; //number to scroll through
    var THUMB_IMG_URL = "http://farm${farm}.static.flickr.com/${server}/${id}_${secret}_s.jpg";
    var LARGE_IMG_URL = "http://farm${farm}.static.flickr.com/${server}/${id}_${secret}_m.jpg";
	
	// !!!
	// NOTE! You must apply for a Flickr API key from http://www.flickr.com/services/api/misc.api_keys.html
	// and insert it below
  var API_KEY_FLICKR = "[INSERT YOUR FLICKR API KEY HERE]";
	
    
    /**
     * Initialization function, sets up variables and requests the landing page image.
     *
     * @param {HTMLElement} container The href value from the base tag.
     * @param {String} reqUrl The URL that should be requested
     * @returns {String} The useable base URL
     * @private
     **/
    function _init(container){
      _d = document;
      _h = _d.getElementsByTagName('head')[0];
      _w = {'preferences':{'searchText':'Nokia'}};
      _d.getElementById('search-input').value = _w.preferences.searchText;
      _g = container;
      var rand = Math.floor(Math.random()*100);
		if ((API_KEY_FLICKR == "[INSERT YOUR FLICKR API KEY HERE]") || (!API_KEY_FLICKR.length) ) {
			document.getElementById('title-bar').innerHTML = 'Flickr API key is needed.';
		}else{
	      _query_flickr("http://api.flickr.com/services/rest/?method=flickr.interestingness.getList&api_key=" + API_KEY_FLICKR + "&format=json&page=" + rand + "&per_page=1");
		}
    }
    
    function _generate_string(template,values){
      return template.replace(/\$\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,function(m,name){
        return values[name] !== undefined ? values[name] : "";
      });
    }
    
    function _splash(results){
        if (results.photos.photo.length > 0) {
			bg_pic = results.photos.photo[0];
			
			if (bg_pic != undefined) {
				_d.getElementById('splash').style.backgroundImage = 'url(' + _generate_string(LARGE_IMG_URL, bg_pic) + ')';
			}
		}
        //re-purpose global API callback to handle search
        _overwrite_callback(function(results){
          _parse_response(results.photos.photo)
        });
    }
	
	
    function _overwrite_callback(fn){
      jsonFlickrApi = fn;
    }
    function _clear_node(n){
      while (n.hasChildNodes()){
        n.removeChild(n.lastChild);
      }
    }
    
    
    function _render_grid(){
      var x = 0;
      for (p in _imgs) {
        if (p >= _focus && p < (_focus +_PER_PAGE)) {
          var s = _d.createElement('span')
          if (_imgs[p] != undefined) {
            a = _d.createElement('a');
            a.setAttribute('onclick', 'flickr_webapp.loadPic(' + p + ')');
            img = _d.createElement('img');
            img.setAttribute('src', _imgs[p]['thumb']);
            img.setAttribute('width', '80');
            img.setAttribute('height', '80');
            img.setAttribute('class', 'thumb');			
            s.appendChild(a).appendChild(img);
          }
          else {
            img = _d.createElement('img');
            img.setAttribute('src', 'img/spacer.gif');
            img.setAttribute('width', '80');
            img.setAttribute('height', '80');
            s.appendChild(img);
          }
          _g.appendChild(s);
        }
      }
    } 
     
    
    function _load_pic(index){
      _focus = index;
      _clear_node(_d.getElementById('zoom-container'));
      var table = _d.createElement('table');
      var row = table.insertRow(0);
      table.setAttribute('cellspacing',0);
      table.setAttribute('cellpadding',0);
      _insertZoomedCell(row, index-1)
      _insertZoomedCell(row, index)
      _insertZoomedCell(row, index+1)
      
      _d.getElementById('zoom-container').appendChild(table);
      
      mwl.switchClass('#zoom-container','zoom*','zoom2');
      mwl.setGroupTarget('#search-button','#grid','visible','hidden');
      mwl.setGroupTarget('#content', '#zoom', 'visible', 'hidden');
    }
    
    function _slide_left(){
      mwl.setGroupTarget('#arrow-button','#set2','visible','hidden');
      _load_pic(_focus - 2);
    }
    
    function _slide_right(){
      mwl.setGroupTarget('#arrow-button','#set2','visible','hidden');
      _load_pic(_focus + 2);
    }
    
    function _insertZoomedCell(row, index){
      var cell = row.insertCell(row.cells.length);
      div = _d.createElement('div');
      div.setAttribute('class','zoom-pic');
      div.style.backgroundImage = 'url(' + _imgs[index].large + '?d=' + new Date().valueOf() + ')';
      cell.appendChild(div);
      title = _d.createElement('div');
      title.setAttribute('class','title');
      title.innerHTML = _imgs[index].title;
      div.appendChild(title);
      return cell;
    }
    
    function _query_flickr(url){
      if (_s != undefined) {
        _h.removeChild(_s);
      }
      _s = document.createElement('script');
      _s.type = 'text/javascript';
      _s.src = url;
	  try { // Chec if there's problem in adding the content in DOM header
	  	_h.appendChild(_s);
	  } catch (e) {
	  	no_results();
	  }
    }
	function _no_results() { // In case of search fails / no results available
		document.getElementById("grid-container").innerHTML = "No results";
	}
    function _parse_response(photos){
      var num_results = photos.length;
      if (num_results > 15) {
        _focus = Math.round(num_results/2);
        _imgs = {};
        for (p = 0; p < photos.length; p++) {
          _imgs[p] = {
            'title': photos[p].title,
            'thumb': _generate_string(THUMB_IMG_URL, photos[p]),
            'large': _generate_string(LARGE_IMG_URL, photos[p])
          };
        }
        _render_grid(_imgs);
      }else{
	  	no_results();
        //alert('No results found.');
      }
    }
    
    function _search(){
      //establish interface
      _clear_node(_g);
      mwl.setGroupTarget('#content','#grids','visible','hidden');
      //get/validate search string
      var text = text || _d.getElementById('search-input').value;
      if (text.length != 0) {
        _w.preferences['searchText'] = text;
        _query_flickr("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=" + API_KEY_FLICKR + "&format=json&page=1&per_page=" + _BUFFER + "&text=" + text);
      }
    }
    
    return {
      init:_init,
      search:_search,
      splash:_splash,
      loadPic:_load_pic,
      slideLeft:_slide_left,
      slideRight: _slide_right,
      parse_response:_parse_response
    }
  }();
  if(typeof window.addEventListener !== 'undefined') {
    window.addEventListener('load', function() { flickr_webapp.init(document.getElementById('grid-container')); }, false);
  }else if(typeof window.attachEvent !== 'undefined') {
    window.attachEvent('onload', function() { flickr_webapp.init(document.getElementById('grid-container')); });
  }
} )();